#include <iostream>
#include <string>
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

#include "Log.hpp"

using namespace qihai;

int main(int argc, char* argv[])
{
    if (argc != 3)
    {
        LOG(FATAL) << "./tcpclient server_ip server_port\n";
        return 1;
    }

    // 1.创建套接字
    int clientSockt = socket(AF_INET, SOCK_STREAM, 0);  // AF_INET IPV4 SOCK_STREAM 流式-字节流(TCP) 0自动推导
    if (clientSockt < 0)
    {
        // 差错处理
        LOG(FATAL) << "socket error...\n";
        exit(errno);
    }

    // 确定服务器信息
    struct sockaddr_in server;
    memset(&server, 0, sizeof server);
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(argv[1]);
    server.sin_port = htons(atoi(argv[2]));

    // 客户端不需要绑定,TCP需要对服务器进行连接
    if (0 > connect(clientSockt, (sockaddr*)&server, sizeof server))
    {
        LOG(FATAL) << "服务器未连接成功.....\n";
        return 2;
    }
    // 业务开始
    char buffer[1024] = {0};
    while (true)
    {
        std::string message;
        std::cout << "enter# ";
        std::getline(std::cin, message);

        ssize_t sendLen = send(clientSockt, message.c_str(), message.size(), 0);
        if (sendLen < 0)
        {
            // 差错处理
            LOG(WARNING) << "send lose......\n";
            continue;
        }

        ssize_t n = recv(clientSockt, buffer, sizeof(buffer) - 1, 0);
        if (n < 0)
        {
            // 接收失败
            LOG(WARNING) << "recv lose.....\n"; 
        }
        else if (n == 0)
        {
            // 服务端关闭了连接
            LOG(DEBUG) << "server close link......\n"; 
            break;
        }
        else{
            buffer[n] = '\0';
            LOG(INFO) << "server# " << buffer << "\n";
        }
    }
    close(clientSockt);
    return 0;
}